<?php

/* * *********************************
 * UniPortal - MY_Controller module
 * @Author: Le Thuy Trieu
 * @date: 2011/12/28
 * ******************************** */

class MY_Controller extends CI_Controller
{
	var $secure = 0;
	
    var $language = "english";
    var $required_roles = array();
	var $current_year = 0;
	var $is_mainternance = MAINTERNANCE;
	
	var $menu = array(
		'catalog' => array()
	);
   
    function __construct()
    {
        parent::__construct();
		
		// $sections = array(
			// 'config'  => TRUE,
			// 'queries' => TRUE
			// );

        if ( !empty($this->is_mainternance)) {
        	redirect(site_url('mainternance/index'));
        //	die();
        }
        
		// $this->output->set_profiler_sections($sections);
		$this->load->helper('cookie');
		
		//secure
		if($this->secure) {
			$this->_check_login();
		}
		
		//language
		$this->language = get_cookie("slcLanguage", "vietnam");
		if(empty($this->language)){$this->language = "vietnam";}
		$this->lang->load('common', $this->language);
// 		try {
// 			$this->lang->load(strtolower(get_class($this)), $this->language);
// 		} catch (Exception $e) {
			
// 		}
		
		//$this->lang->load('form_validation', $this->language);
		
		$this->load->library('encrypt');
		
		//load menus
		$this->render_leftmenu();
		
    }
    
	function render_leftmenu(){
	}
	
	// Secure
	protected function _is_connect(){
		$username = $this->session->userdata('email');
		return !empty($username);
	}
	
	protected function _check_login(){
		if(!$this->_is_connect()){
			redirect(site_url('login/index'));
		}
	}
	
	protected function _check_module($mid){
		$valid = false;
		$code = $this->session->userdata('code');
		if(!empty($code)){
			$modules = explode(',', $code);
			foreach($modules as $module){
				if($module === $mid){
					$valid = true;
					break;
				}
			}
		}
		return $valid;
	}
	
	protected function _get_current_year(){
		return $this->session->userdata('year');
	}
	
	protected function _get_current_term(){
		return $this->session->userdata('term');
	}
	
	protected function _get_current_yearterm(){
		return $this->session->userdata('yearterm');
	}
	
	function _get_userid(){
		return $this->session->userdata('userid');
	}
	
	function _get_username(){
		return $this->session->userdata('username');
	}
	
	// End Secure
	
    function isAjax()
    {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest");
    }
	
	//CRUD
	// get data format as rows from data
	function _get_row($data){
		
		$fields = array();
		foreach($data as $field => $values){
			$fields[] = $field;
		}
		
		$rows = array();
		foreach($data[$fields[0]] as $index => $value){
			$row = array();
			foreach($fields as $field){
				$row[$field] = $data[$field][$index];
			}
			$rows[] = $row;
		}
		
		return $rows;
	}
	
	//New row
	
	function new_row(){
		
		extract($_POST, EXTR_OVERWRITE);
		
		if (!$this->db->table_exists($table_name)){
			die('no table found.');
		}
		
		$fielddata = $this->db->field_data($table_name);
		$format_fields = array();
		
		if(!empty($fields)) {
			foreach($fields as $field){
				if(!$this->db->field_exists($field, $table_name)){
					show_error('Field not exist');
				} else {
					foreach($fielddata as $key => $value){
						if($value->name === $field) {
							$format_fields[] = $value;
							break;
						}
					}
				}
			}
		} else {
			$format_fields = $fielddata;
		}
		
		$row_id = uniqid();
		$html = "<tr id='$row_id' class='new-row'>";
		$this->load->model(ucfirst($table_name).'_model', $table_name);
		foreach($format_fields as $field){
			$class =  $field->primary_key ? 'required' : '';
			$name = $table_name . '[' . $field->name . '][]';
			$id = $table_name . '_' . $field->name . $row_id;
			$fkey = $this->$table_name->_get_fkey($field->name);
			if(!empty($fkey)) {
				$model_name = $fkey[0];
				$this->load->model($fkey[0], $model_name);
				$this->load->helper('form');
				$items = $this->$model_name->getAll();
				
				$selectbox_items = get_select_array($items, $this->$model_name->display_field, $fkey[1]);
				
				$html .= '<td>' . form_dropdown($name, $selectbox_items, $value) . '</td>';
			} else {
				switch($field->type){
					case 'varchar':
						$html .= "<td><input type='text' class='$class' name='$name' id='$id' maxlength=" 
								. $field->max_length . " ></td>";
						break;
					case 'int':
						$html .= "<td><input type='text' class='$class number' name='$name' id='$id' ></td>";
						break;
					case 'datetime':
					case 'date':
						$html .= "<td><input type='text' class='$class datepicker' name='$name' id='$id' ></td>";
						break;
				}	
			}
		}
		$html .= "<td><a href='javascript:void(0)' onclick=\"removeRow('$row_id')\">delete</a></td></tr>";
		
		if( $this->isAjax() ){
			echo $html;
		} else {
			return $html;
		}
	}
	
	function crud_form($model, $fields, $row = array()){
	
		$html = '';
		
		foreach($fields as $field){
			$value = empty($row[$field]) ? '' : $row[$field];
			$html .= $this->_form_row($model, $field, $value);
		}
		
		return $html;
	}

	function form_row($table_name, $field, $value){
		$model_name = ucfirst($table_name) . '_model';
		$this->load->model($model_name, $table_name);
		$this->_form_row($this->$table_name, $field, $value);
	}
	
	function _form_row($model, $field, $value = ''){
		
		if (!$this->db->table_exists($model->table_name)){
			show_error('no table found.');
		}
		
		$fielddata = $this->db->field_data($model->table_name);
		
		if(!$this->db->field_exists($field, $model->table_name)){
			show_error('Field not exist');
		} else {
			foreach($fielddata as $key => $ffield){
				if($ffield->name === $field) {
					$format_field = $ffield;
					break;
				}
			}
		}
	
		$id = $model->table_name . "_" . $field;
		$data = array(
			'id' => $id,
			'field' => $field,
			'table' => $model->table_name,
			'value' => $value,
			'max_length' => $format_field->max_length,
			'class' =>  ($format_field->primary_key ? 'required' : '')
		);
		
		$template = '';
		$fkey = $model->_get_fkey($field);
		if(!empty($fkey)) {
			$template = 'crud/view_relation_input';
			
			$model_name = $fkey[0];
			$this->load->model($fkey[0], $model_name);
			$this->load->helper('form');
			$items = $this->$model_name->getAll();
			
			$selectbox_items = get_select_array($items, $this->$model_name->display_field, $fkey[1]);
			
			$data['selectbox'] = form_dropdown("row[$field]", $selectbox_items, $value, array('class' => $data['class']));
		} else {
			switch($format_field->type){
				case 'varchar':
					$template = 'crud/view_text_input';
					break;
				case 'int':
					$template = 'crud/view_number_input';
					break;
				case 'datetime':
					$template = 'crud/view_date_input';
					break;
				case 'tinyint':
					$template = 'crud/view_checkbox_input';
					break;
				default:
					$template = 'crud/view_text_input';
					break;
			}
		}	
			
		$html = $this->parser->parse($template, $data, TRUE );
		
		if( $this->isAjax() ){
			echo $html;
		} else {
			return $html;
		}
	}
	
	function _get_controller(){
		$controller = $this->uri->segment(1);
		return $controller;
	}
	
	function view_list($model = '', $from = 0, $sortby = '', $orderby = ''){
		
		$table = strtolower($model);
		$controller = $this->_get_controller();
		
		if(empty($model) || !$this->db->table_exists($table) || empty($this->display_field[$model])) {
			show_404('page not found');
		}
		
		$this->load->model(ucfirst($model).'_model', 'model');
		
		//pagination
		$page_size = config_item('page_size');
		$search_key = $this->input->post('search_key');
		
		$rows = $this->model->_find_page($search_key, $this->display_field[$model], 
			($from/$page_size), $page_size, $sortby, $orderby );
		
		if(!empty($search_key)){
			$this->session->set_flashdata('search_key', $search_key);
		} else {
			$search_key = $this->session->flashdata('search_key');
			$this->session->keep_flashdata('search_key');
		}
		
		$config['base_url'] = site_url("$controller/view_list/$model");
        $config['total_rows'] = $this->model->_count_all_results($search_key, $this->display_field[$model]);
        $config['uri_segment'] = 4;
        $config['per_page'] = $page_size;
        $this->pagination->initialize($config);
		// echo $config['total_rows'];
			
		//crud table
		$fields = $this->display_field[$model];
		$columnsizes = $this->display_format[$model];
		
		$crud = array(
			'list_handler' => "$controller/view_list/$model",
			'delete_handler' => "$controller/delete_item/$model",
			'show_handler' => "$controller/show_item/$model",
			'form_handler' => "$controller/create_item/$model",
			'primary_key' => $this->model->primary_key,
			'rows' => $rows,
			'fields' => $fields,
			'columnsizes' => $columnsizes,
			'sortby' => $sortby,
			'orderby' => $orderby,
			'page' => $from
		);
		
		$crud = $this->_modify_list($model, $crud);
		
		foreach($fields as $i => $field){
			$fields[$i] = "'" . $fields[$i] . "'";
		}
		// echo $this->display_format[$model]['use_ajax'];
		// die();
		$use_ajax = 0;
		if ( !empty($this->display_format[$model]['use_ajax'])) {
			$use_ajax = 1;
		}
		$data = array(
			'add_link' => empty($use_ajax) ? site_url("$controller/blank/$model") : '',
			'add_link_js' => "newRow('$table', new Array(". implode(',', $fields) .") )", 
			'pagination' => $this->pagination->create_links(),
			'table' => $this->table->_crudtable($this->parser, $crud),
			'searchbox' => $this->table->_searchbox($this->parser, "$controller/view_list/$model", $search_key),
			'title' => (empty($this->display_format[$model]['list_title']) ? $model : $this->display_format[$model]['list_title']),
			'add_title' => (empty($this->display_format[$model]['list_add']) ? lang('common_add') : $this->display_format[$model]['list_title'])
		);
		
		$this->template->parse_view('rightcontent', 'crud/view_list', $data);
		$this->template->render(); 
	}
	
	function create_item($model = ''){
		
		$table = strtolower($model);
		$controller = $this->_get_controller();
		if(empty($model) || !$this->db->table_exists($table)) {
			show_404('page not found');
		}
		echo $_POST[$table];
		if(!empty($_POST[$table])){
			$this->load->model($model.'_model', 'model');
			
			$rows = $this->_get_row($_POST[$table]);
			foreach($rows as $i => $row){
				$rows[$i] = $this->_modify_create($model, $row);
			}
			$this->model->_insert_row($rows);
		}
		redirect(site_url("$controller/view_list/$model")); 
	}
	
	function show_item($model = '', $key = 0, $from = 0){
		$controller = $this->_get_controller();
		$table = strtolower($model);
		if(empty($model) || !$this->db->table_exists($table)) {
			show_404('page not found');
		}
		
		$this->load->model($model.'_model', 'model');
		$row = $this->model->_find_by_key(array($this->model->primary_key => $key));
		notFoundIfNull($row);
		
		$data = array(
			'id' => $key,
			'form' => $this->crud_form($this->model, $this->display_field[$model], $row),
			'update_link' => site_url("$controller/update_item/$model/$key"),
			'list_link' => site_url("$controller/view_list/$model/$from"),
		);
		$this->template->parse_view('rightcontent', 'crud/view_show', $data);
		$this->template->render();
	}
	function blank($model = '', $from = 0) {
		$controller = $this->_get_controller();
		$table = strtolower($model);
		if(empty($model) || !$this->db->table_exists($table)) {
			show_404('page not found');
		}
		
		$this->load->model($model.'_model', 'model');
		
		$data = array(
			'form' => $this->crud_form($this->model, $this->display_field[$model]),
			'update_link' => site_url("$controller/create_item/$model"),
			'list_link' => site_url("$controller/view_list/$model/$from"),
		);
		$this->template->parse_view('rightcontent', 'crud/view_show', $data);
		$this->template->render();
	}
	
	function update_item($model, $id = 0){
		$controller = $this->_get_controller();
		extract($_POST, EXTR_OVERWRITE);
		$table = strtolower($model);
		if(empty($model) || !$this->db->table_exists($table)) {
			show_404('page not found');
		}
		
		$this->load->model($model.'_model', 'model');
		$item = $this->model->_find_by_key(array($this->model->primary_key => $id));
		notFoundIfNull($item);
		$row = $this->_modify_update($model, $row);
		$this->model->_update($row, array($this->model->primary_key => $id));
		redirect(site_url("$controller/view_list/$model"));
	}
	
	function _modify_update($model, $data){
		return $data;
	}
	
	function _modify_create($model, $data){
		return $data;
	}
	
	function _modify_list($model, $data){
		return $data;
	}
    
    
    function add_jQueryMobile_css(){
        $this->template->add_css('css_m/jquery.mobile-1.2.0.css');
        //$this->template->add_css('css_m/my.css');
        
    }
    
    function add_jQueryMobile_js(){
        $this->template->add_js('js_m/jquery-1.8.2.min.js');
        $this->template->add_js('js_m/jquery.mobile-1.2.0.min.js');
        //$this->template->add_js('js_m/my.js');
    }
}